namespace ResumableDownload.View.Converters
{
    using System;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Data;
    using WP7Contrib.Services.DownloadManager;

    public sealed class RequestRemainingToStringConverter : IValueConverter
    {
        private const int KiloByte = 1024;

        public static NumberFormatInfo NumberFormatInfo;

        public readonly string RemainingFormat = "Remaining time: {0} ";

        static RequestRemainingToStringConverter()
        {
            NumberFormatInfo = (NumberFormatInfo)CultureInfo.CurrentUICulture.NumberFormat.Clone();
            NumberFormatInfo.NumberDecimalDigits = 0;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var request = value as FileRequest;

            if (request == null || value == DependencyProperty.UnsetValue)
            {
                return DependencyProperty.UnsetValue;
            }

            var contentLength = request.ContentLength;
            var fileLength = request.FileLength;
            var rate = request.DownloadRate * KiloByte;

            if (contentLength == 0 || fileLength == 0 || Equals(rate, 0))
            {
                return string.Format(RemainingFormat, "0 secs");
            }

            var remainingLength = contentLength - fileLength;
            var remainingTime = (int)(remainingLength / rate);

            var ts = TimeSpan.FromSeconds(remainingTime);

            var duration = string.Empty;
            if (ts.TotalSeconds < 60)
            {
                duration = ts.TotalSeconds.ToString("N", NumberFormatInfo) + " secs";
            }
            else
            {
                if (ts.TotalMinutes < 60)
                {
                    duration = ts.Minutes.ToString("N", NumberFormatInfo) + " mins " + ts.Seconds.ToString("N", NumberFormatInfo) + " secs";
                }
                else
                {
                    duration = ts.Hours.ToString("N", NumberFormatInfo) + " hrs " + ts.Minutes.ToString("N", NumberFormatInfo) + " mins";
                }
            }
            
            return string.Format(RemainingFormat, duration);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }
}